<template>
  <div class="page-container">
    <head-component></head-component>
    <div class="main-container">
      <aside-component></aside-component>
      <div class="content-container">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>订单管理</span>
              <div class="search-inputs">
                <el-input
                  v-model="searchQuery"
                  placeholder="请输入订单号或用户名"
                  clearable
                  style="width: 250px; margin-right: 10px;"
                  @keyup.enter="handleSearch"
                />
                <el-button type="primary" @click="handleSearch">搜索</el-button>
              </div>
            </div>
          </template>
          <el-table :data="orders.list" style="width: 100%" v-loading="loading" empty-text="暂无订单数据">
            <el-table-column prop="orderNum" label="订单号" width="180">
              <template #default="scope">
                <span v-html="highlightMatch(scope.row.orderNum, searchQuery)"></span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="收货人" width="100">
              <template #default="scope">
                <span v-html="highlightMatch(scope.row.name, searchQuery)"></span>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="联系电话" width="120" />
            <el-table-column prop="address" label="收货地址" width="200" show-overflow-tooltip />
            <el-table-column prop="totalPrice" label="总价" width="100">
              <template #default="scope">
                ¥{{ scope.row.totalPrice }}
              </template>
            </el-table-column>
            <el-table-column prop="state" label="订单状态" width="100">
              <template #default="scope">
                <el-tag :type="getOrderStateType(scope.row.state)">
                  {{ getOrderStateText(scope.row.state) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" width="150" show-overflow-tooltip />
            <el-table-column prop="createTime" label="创建时间" width="160" />
            <el-table-column prop="updateTime" label="更新时间" width="160" />
            <el-table-column label="操作" fixed="right" width="150">
              <template #default="scope">
                <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
                <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 15, 20, 25, 50]"
              :total="orders.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </div>
    </div>
    <foot-component></foot-component>
  </div>

  <!-- 编辑订单对话框 -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
    <el-form :model="currentOrder" :rules="editRules" ref="editOrderForm" label-width="100px">
      <el-form-item label="订单号" prop="orderNum">
        <el-input v-model="currentOrder.orderNum" disabled></el-input>
      </el-form-item>
      <el-form-item label="收货人" prop="name">
        <el-input v-model="currentOrder.name" placeholder="请输入收货人姓名"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="currentOrder.phone" placeholder="请输入联系电话"></el-input>
      </el-form-item>
      <el-form-item label="收货地址" prop="address">
        <el-input v-model="currentOrder.address" type="textarea" :rows="2" placeholder="请输入收货地址"></el-input>
      </el-form-item>
      <el-form-item label="订单状态" prop="state">
        <el-select v-model="currentOrder.state" placeholder="请选择订单状态">
          <el-option label="待付款" :value="5"></el-option>
          <el-option label="待发货" :value="1"></el-option>
          <el-option label="待收货" :value="2"></el-option>
          <el-option label="已完成" :value="3"></el-option>
          <el-option label="已取消" :value="4"></el-option>
          <el-option label="已退款" :value="6"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单总价" prop="totalPrice">
        <el-input-number v-model="currentOrder.totalPrice" :min="0" :precision="2" :step="0.1" disabled></el-input-number>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="currentOrder.remark" type="textarea" :rows="2" placeholder="请输入备注信息"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ElMessage, ElMessageBox } from 'element-plus'
import AsideComponent from '../components/Aside.vue'
import HeadComponent from '../components/Head.vue'
import FootComponent from '../components/Foot.vue'

export default {
  name: 'OrdersManger',
  components: {
    AsideComponent,
    HeadComponent,
    FootComponent
  },

  data () {
    return {
      orders: {
        total: 0,
        list: [],
        pageSize: 10,
        pageNum: 1
      },
      loading: false,
      currentPage: 1,
      pageSize: 10,
      searchQuery: '',
      dialogVisible: false,
      dialogTitle: '编辑订单',
      currentOrder: {},
      editRules: {
        name: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入收货地址', trigger: 'blur' }
        ],
        state: [
          { required: true, message: '请选择订单状态', trigger: 'change' }
        ]
      }
    }
  },

  mounted () {
    this.getAllOrders()
  },

  watch: {
    searchQuery (newValue, oldValue) {
      if (!newValue && oldValue) {
        this.currentPage = 1
        this.getAllOrders()
      }
    }
  },

  methods: {
    // 获取所有订单
    getAllOrders () {
      this.loading = true
      this.$ajax.get('/admin/orders/selectAllOrders', {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize
        }
      })
        .then((response) => {
          const resp = response.data
          if (resp.code === 0) {
            this.orders = { ...resp.data }
            this.currentPage = resp.data.pageNum
            this.pageSize = resp.data.pageSize
          } else {
            ElMessage.error(resp.msg)
          }
        })
        .catch((error) => {
          console.error('获取订单列表失败:', error)
          ElMessage.error('获取订单列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 处理搜索
    handleSearch () {
      // 判断搜索关键字是否为空
      if (!this.searchQuery) {
        ElMessage.warning('请输入关键字！')
        return
      }

      this.loading = true
      // 先清空当前列表，避免显示旧数据
      this.orders.list = []

      this.$ajax.get('/admin/orders/selectLikeOrderNumOrName', {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          keywords: this.searchQuery
        }
      })
        .then((response) => {
          const resp = response.data
          if (resp.code === 0) {
            // 只有在有数据时才更新列表
            if (resp.data.list && resp.data.list.length > 0) {
              this.orders = { ...resp.data }
              this.currentPage = resp.data.pageNum
              this.pageSize = resp.data.pageSize
            } else {
              // 没有搜索结果时，只更新总数和分页信息
              this.orders = {
                total: 0,
                list: [],
                pageSize: this.pageSize,
                pageNum: 1
              }
            }
          } else {
            ElMessage.error(resp.msg)
            // 发生错误时也清空列表
            this.orders.list = []
          }
        })
        .catch((error) => {
          console.error('搜索订单失败:', error)
          ElMessage.error('搜索订单失败')
          // 发生错误时清空列表
          this.orders.list = []
        })
        .finally(() => {
          this.loading = false
        })
    },

    // 处理页码改变
    handleSizeChange (val) {
      this.pageSize = val
      this.getAllOrders()
    },

    // 处理每页条数改变
    handleCurrentChange (val) {
      this.currentPage = val
      this.getAllOrders()
    },

    // 获取订单状态对应的类型
    getOrderStateType (state) {
      const stateMap = {
        1: 'success', // 已支付，待发货
        2: 'primary', // 已发货，待收货
        3: 'success', // 已收货
        4: 'danger', // 已取消
        5: 'warning', // 未支付，待付款
        6: 'info' // 已退款
      }
      return stateMap[state] || 'info'
    },

    // 获取订单状态文本
    getOrderStateText (state) {
      const stateMap = {
        1: '待发货',
        2: '待收货',
        3: '已完成',
        4: '已取消',
        5: '待付款',
        6: '已退款'
      }
      return stateMap[state] || '未知状态'
    },

    // 查看订单详情
    handleView (row) {
      // TODO: 实现查看订单详情功能
      ElMessage.info('查看订单详情功能开发中...')
    },

    // 删除订单
    handleDelete (row) {
      ElMessageBox.confirm(
        '确定要删除该订单吗？',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 调用删除接口
        const orderId = row.orderId // 获取订单ID
        this.$ajax.delete(`/admin/orders/deleteOrders?orderId=${encodeURIComponent(orderId)}`)
          .then(response => {
            const resp = response.data
            if (resp.code === 0) {
              ElMessage.success('订单删除成功')
              this.getAllOrders() // 删除成功后刷新列表
            } else {
              ElMessage.error(resp.msg || '订单删除失败')
            }
          })
          .catch(error => {
            console.error('删除订单失败:', error)
            ElMessage.error('删除订单失败，请稍后重试')
          })
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    },

    // 编辑订单
    handleEdit (row) {
      this.dialogVisible = true
      this.dialogTitle = '编辑订单'
      // 复制订单数据到 currentOrder，保留 orderId
      this.currentOrder = {
        orderId: row.orderId, // 保留 orderId 用于提交
        orderNum: row.orderNum,
        name: row.name,
        phone: row.phone,
        address: row.address,
        state: row.state,
        totalPrice: row.totalPrice,
        remark: row.remark
      }
      // 重置表单验证状态
      if (this.$refs.editOrderForm) {
        this.$refs.editOrderForm.resetFields()
      }
    },

    // 提交编辑
    submitEdit () {
      this.$refs.editOrderForm.validate((valid) => {
        if (valid) {
          // 确保提交时包含 orderId
          const submitData = {
            orderId: this.currentOrder.orderId,
            name: this.currentOrder.name,
            phone: this.currentOrder.phone,
            address: this.currentOrder.address,
            state: this.currentOrder.state,
            remark: this.currentOrder.remark
          }
          this.$ajax.post('/admin/orders/updateOrders', submitData)
            .then(response => {
              if (response.data.code === 0) {
                ElMessage.success('订单更新成功')
                this.dialogVisible = false
                this.getAllOrders() // 刷新订单列表
              } else {
                ElMessage.error(response.data.msg || '订单更新失败')
              }
            })
            .catch(error => {
              console.error('更新订单失败:', error)
              ElMessage.error('更新订单失败，请稍后重试')
            })
        }
      })
    },

    // 关键字高亮显示
    highlightMatch (text, query) {
      if (!query) {
        return text
      }
      // 仅处理文本高亮，不涉及数字（如价格）
      const regex = new RegExp(query, 'gi')
      return text.toString().replace(regex, match =>
        `<span style="color: red; font-weight: bold;">${match}</span>`
      )
    }
  }
}
</script>

<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

.main-container {
  display: flex;
  flex: 1;
}

.content-container {
  flex: 1;
  padding: 0;
  background-color: #f5f7fa;
  height: 100%;
  width: 100%;
  overflow-y: auto;
}

.box-card {
  margin-bottom: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-inputs {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
